package com.kaibes.module.encryption.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaibes.core.spring.proxy.Proxy;
import com.kaibes.web.encryption.EncryptionKey;
import com.kaibes.web.encryption.EncryptionKeyService;

@Service
public class EncryptionKeyServiceImpl implements EncryptionKeyService {

    @Proxy
    private EncryptionClient encryptionClient;
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public boolean saveKey(EncryptionKey key) {
        try {
            encryptionClient.saveByKey(key.getClass().getName(), objectMapper.writeValueAsString(key));
            return true;
        } catch (JsonProcessingException e) {
            return false;
        }
    }

    @Override
    public EncryptionKey getKey() {
        String value = encryptionClient.getByKey(EncryptionKey.class.getName());
        try {
            EncryptionKey key = objectMapper.readValue(value, EncryptionKey.class);
            return key;
        } catch (JsonProcessingException e) {
            return null;
        }
    }

}
